﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
using System.Net;

namespace revoStore
{
    class PackageOld
    {
         #region "Proprietes"
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private AppOld _application;
        public AppOld Application
        {
            get { return _application; }
            set { _application = value; }
        }

        private string _filepath;
        public string FilePath
        {
            get { return _filepath; }
            set { _filepath = value; }
        }

        private byte[] _setupFile;
        public byte[] SetupFile
        {
            get { return _setupFile; }
            set { _setupFile = value; }
        }

        private byte[] _uninstFile;
        public byte[] UninstFile
        {
            get { return _uninstFile; }
            set { _uninstFile = value; }
        }
        #endregion






        public PackageOld(string packageFile, bool runInstall = true)
        {
            this.FilePath = packageFile;

            var zip = new ZipInputStream(File.OpenRead(@packageFile));
            var filestream = new FileStream(@packageFile, FileMode.Open, FileAccess.Read);
            ZipFile zipfile = new ZipFile(filestream);
            ZipEntry item;
            bool app = false;
            bool set = false, unin = false;
            while ((item = zip.GetNextEntry()) != null)
            {
                //Console.WriteLine(item.Name);
                using (StreamReader s = new StreamReader(zipfile.GetInputStream(item)))
                {
                    // stream with the file
                    //Console.WriteLine(s.ReadToEnd());

                    
                    if (item.Name == "app.pkg")
                    {
                        this.Application = new AppOld(s.ReadToEnd(), true);
                        if (this.Application.down) this.Download = true;
                       // System.Windows.Forms.MessageBox.Show(this.Application.SetupFile);
                        this.SetupFile = this.Application.Setup;
                        if ((this.Application.UninstFile == null) || (string.IsNullOrEmpty(this.Application.UninstFile)) || (string.IsNullOrWhiteSpace(this.Application.UninstFile)))
                        {

                        }
                        else
                        {
                            this.UninstFile = this.Application.Uninstall;
                        }
                            this.Name = this.Application.Name;
                        app = true;
                    }
                    if (!app) continue;
                    if (item.Name == this.Application.SetupFile)
                    {
                        if (!app) continue;
                        this.Application.Setup = System.Text.Encoding.UTF8.GetBytes(s.ReadToEnd());
                        set = true;
                    }
                    if (item.Name == this.Application.UninstFile)
                    {
                        if (!app) continue;
                        this.Application.Uninstall = System.Text.Encoding.UTF8.GetBytes(s.ReadToEnd());
                        unin = true;
                    }
                    
                }
            }
            if (!app || !set/* || !unin*/)
            {
                if (!Download)
                {
                    System.Windows.Forms.MessageBox.Show("Error: The specified package file is corrupted and/or invalid.");
                    //break;
                    return;
                }
            }


            



            //_application = new App(packageFile, false);
        }

        public void runInst()
        {
           
           
                Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "revoStore", "Temp", (this.Application.Name + '_' + DateTime.Now.Year + '_' + DateTime.Now.Month + '_' + DateTime.Now.DayOfYear + '_' + DateTime.Now.Hour + '_' + DateTime.Now.Minute + '_' + DateTime.Now.Second)));
                this.runInstall(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "revoStore", "Temp", (this.Application.Name + '_' + DateTime.Now.Year + '_' + DateTime.Now.Month + '_' + DateTime.Now.DayOfYear + '_' + DateTime.Now.Hour + '_' + DateTime.Now.Minute + '_' + DateTime.Now.Second)));
          
        }

        /*public Package(Int32 id)
        {
            /*SQL sq = new SQL(revoStore.Vars.sqlHost, revoStore.Vars.sqlUser, revoStore.Vars.sqlPass, revoStore.Vars.sqlDB);

            string query = "SELECT * FROM apps WHERE ID='" + id + "'";

            dynamic g = sq.GetRow(query);

            this.ID = g(0);
            this.Name = g(1);
            this.Version = g(2);
            this.Creator = g(3);
            this.Type = g(4);
            this.Setup = g(5);
        }*/
       public delegate void InstalledEventHandler(object sender, EventArgs e);

       public event InstalledEventHandler Installed;

       public virtual void OnInstalled(EventArgs e)
       {
           if (Installed != null)
               Installed(this, e);
       }

       public Process p;
public WebClient webClient = new WebClient();
        public void runInstall(string launchDir/*, bool copyAllFiles*/)
        {
            if (!Download)
            {
                string packageFile = this.FilePath;
                FastZip f = new FastZip();
                f.ExtractZip(packageFile, launchDir, "");


                p = Process.Start(Path.Combine(launchDir, this.Application.SetupFile));
                p.EnableRaisingEvents = true;

            }
            else
            {
                Downloading = true;
       webClient.DownloadFileCompleted += Setup_Downloaded;
                webClient.DownloadFile(this.Application.SetupFile, Path.Combine(launchDir, Path.GetFileName(this.Application.SetupFile)));
                
         

                p = Process.Start(Path.Combine(launchDir, Path.GetFileName(this.Application.SetupFile)));
                p.EnableRaisingEvents = true;
            }

            //p.Exited += new EventHandler(Setup_Exited);



           
        }
        public bool Download = true;
        public bool Downloading = false;
        public bool Downloaded = true;
        public void Setup_Exited(object sender, EventArgs e)
        {
            //MessageBox.Show("READY");
            OnInstalled(e);
        }

        public void Setup_Downloaded(object sender, EventArgs e)
        {
            Downloading = false;
            Downloaded = true;
        }
    }
}
